package com.tttn.docbao.db;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import com.tttn.docbao.until.Core;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.OpenableColumns;

public class SqliteHelper extends SQLiteOpenHelper {

	private Context context;

	File dbFile;

	public SqliteHelper(Context context) {
		super(context, Core.DATABASE_NAME, null, Core.DATABASE_VERSION);
		this.context = context;
		// dbFile = new File(DB_PATH + DATABASE_NAME);
	}

	@Override
	public synchronized SQLiteDatabase getWritableDatabase() {

		if (!dbFile.exists()) {
			SQLiteDatabase db = super.getWritableDatabase();
			copyDataBase(db.getPath());
		}
		return super.getWritableDatabase();
	}

	@Override
	public synchronized SQLiteDatabase getReadableDatabase() {
		if (!dbFile.exists()) {
			SQLiteDatabase db = super.getReadableDatabase();
			copyDataBase(db.getPath());
		}
		return super.getReadableDatabase();
	}

	// Creating Tables
	@Override
	public void onCreate(SQLiteDatabase db) {
	}

	// Upgrading database
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

	/**
	 * All CRUD(Create, Read, Update, Delete) Operations
	 */

	private void copyDataBase(String dbPath) {
		try {
			InputStream assestDB = context.getAssets().open(Core.DATABASE_NAME);

			OutputStream appDB = new FileOutputStream(dbPath, false);

			byte[] buffer = new byte[1024];
			int length;
			while ((length = assestDB.read(buffer)) > 0) {
				appDB.write(buffer, 0, length);
			}

			appDB.flush();
			appDB.close();
			assestDB.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}